<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图书名" prop="bookName">
        <el-input
          v-model="queryParams.bookName"
          placeholder="请输入图书名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="auther">
        <el-input
          v-model="queryParams.auther"
          placeholder="请输入作者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图书分类" prop="typeId">
        <el-select v-model="queryParams.typeId" >
          <el-option
            v-for="item in typeList"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="出版社" prop="publisher">
        <el-input v-model="queryParams.publisher" ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:book:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:book:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:book:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--  借阅对话框 -->
    <el-dialog
      title="借阅图书提示"
      :visible.sync="diaLoanVisible"
      width="30%"
    >
      <el-form :inline="true" label-width="80px" >
        <el-form-item label="图书名">
          <el-input disabled v-model="form.bookName"></el-input>
        </el-form-item>
        <el-form-item label="预览图">
          <img :src="form.imageUrl"  width="100px" height="100px" alt="">
        </el-form-item>
        <el-form-item label="借阅时间" prop="sentime">
          <el-date-picker clearable
                          v-model="form.sentime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择借阅时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="违规日期" prop="deftime">
          <el-date-picker clearable
                          v-model="form.deftime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择违规日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="押金">
          <el-input v-model="loadPrice" disabled></el-input>
        </el-form-item>
      </el-form>
      <span>

      </span>
      <span slot="footer" class="dialog-footer">
                <el-button @click="diaLoanVisible = false">取 消</el-button>
                <el-button type="primary" @click="loadConfirm">确 定</el-button>
              </span>
    </el-dialog>

    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图书id" align="center" prop="bookId" />
      <el-table-column label="图书名" align="center" prop="bookName" />
      <el-table-column label="作者" align="center" prop="auther" />
      <el-table-column label="图书分类id" align="center" prop="typeName" />
      <el-table-column label="现存数量" align="center" prop="count" >
        <template slot-scope="{row,$index}">
          <p style="color: sandybrown"  v-if="row.count==0">售空</p>
          <p v-else>{{ row.count }}</p>
        </template>
      </el-table-column>>
      <el-table-column label="预览图" align="center" >
        <template slot-scope="{row,$index}">
          <img :src="row.imageUrl"  width="100" height="100" alt="">
        </template>
      </el-table-column>
      <el-table-column label="出版社" align="center" prop="publisher" />
      <el-table-column label="借出次数" align="center" prop="loan" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="borrowBut(scope.row)"
          >借阅</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:book:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:book:remove']"
          >删除</el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改图书表对话框 -->

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图书名" prop="bookName">
          <el-input v-model="form.bookName" placeholder="请输入图书名" />
        </el-form-item>
        <el-form-item label="作者" prop="auther">
          <el-input v-model="form.auther" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="图书分类" prop="typeId">
          <el-select v-model="form.typeId" >
            <el-option
              v-for="item in typeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="现存数量" prop="count">
          <el-input v-model="form.count" placeholder="请输入现存数量" />
        </el-form-item>
        <el-form-item label="预览图" prop="imgurl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/oldcommon/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-change="onChange"
          >
            <img style="max-height: 300px;max-width: 300px;min-width: 100px;min-height: 100px" v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入出版社" />
        </el-form-item>
        <el-form-item label="借出次数" prop="loan">
          <el-input v-model="form.loan" placeholder="请输入借出次数"  :disabled="true"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listBook, getBook, delBook, addBook, updateBook, borrow} from "@/api/system/book";
import {listType} from "@/api/system/type";
import {chanceData, dataAbs} from "@/utils/dataChance";

export default {
  name: "Book",
  data() {
    return {
      diaLoanVisible: false,// 借阅对话框
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      bookList: [],
      typeList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bookName: null,
        auther: null,
        typeId: null,
        count: null,
        imgurl: null,
        status: null,
        publisher: null,
        loan: null
      },
      // 表单参数
      form: {},
      shopcart:{}, // 借阅信息表
      // 表单校验
      rules: {
      },
      loadData:[]
    };
  },
  computed:{
    loadPrice(){ // 借阅押金
      let {sentime,deftime} = this.form
  return dataAbs(sentime,deftime)*0.3
    }
  },
  created() {
    this.getList();
  },
  methods: {
    borrowBut(row){
      this.reset()
      this.form = Object.assign({},row)
      this.diaLoanVisible = true
    },
    //  图书借阅
    async loadConfirm(){
    //      整理参数
      this.shopcart.bookId = this.form.bookId
      this.shopcart.sentime = this.form.sentime
      this.shopcart.deftime = this.form.deftime
      this.shopcart.forfeit = this.loadPrice

      let res = await borrow(this.shopcart)
      if(res.code==200) this.$message.success(`《${this.form.bookName}》 借阅成功`)
      this.diaLoanVisible = false
      this.form ={}
      this.loadData=[]
    },
    handleAvatarSuccess(response, file, fileList) {
      if (response.code === 0 ) {
        window.top.location.href = '/dev-api/login'
      } else {
        this.form.imgurl = response.msg
        this.form.imageUrl=`/dev-api/oldcommon/download?name=${this.form.imgurl}`
      }
    },
    onChange(file) {
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if (!size) {
          this.$message.error('上传文件大小不能超过 2MB!')
          return false
        }
        return file
      }
    },
    /** 查询【请填写功能名称】列表 */
     getList() {
      this.loading = true;
      listBook(this.queryParams).then(response => {
        this.bookList = response.rows;
        this.bookList.map(item => item.imageUrl = `/dev-api/oldcommon/download?name=${item.imgurl}`)
        this.total = response.total;
        this.loading = false;
      });
      listType({pageNum: 1,
        pageSize: 10}).then(res=>{
          this.typeList = res.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bookId: null,
        bookName: null,
        auther: null,
        typeId: null,
        count: null,
        imgurl: null,
        imageUrl:null,
        status: null,
        publisher: null,
        loan: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bookId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加图书";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const bookId = row.bookId || this.ids
      getBook(bookId).then(response => {
        this.form = response.data;
        this.$set(this.form,"imageUrl",`/dev-api/oldcommon/download?name=${this.form.imgurl}`)
        this.open = true;
        this.title = "修改图书";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.bookId != null) {
            updateBook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBook(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bookIds = row.bookId || this.ids;
      // const bookname = row.bookName || this.
      this.$modal.confirm('是否确认删除图书编号为"' + bookIds + '"的数据项？').then(function() {
        return delBook(bookIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/book/export', {
        ...this.queryParams
      }, `book_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
